<template>
  <div class="bgs">
    <div class="title container bg-fff">{{ title }}</div>
    <van-radio-group v-model="curRegType" v-if="is_select == 'true'">
      <div class="regType">
        <span v-if="mobile">
          {{$t("verify.title_phone")}}
          <van-radio checked-color="#FF710B" :name="0"></van-radio>
        </span>
        <span v-if="email">
          {{$t("verify.title_email")}}
          <van-radio checked-color="#FF710B" :name="1"></van-radio>
        </span>
      </div>
    </van-radio-group>
    <ul class="list container bg-fff">
      <li class="db" v-if="curRegType == 0">
        <div class="name">{{$t("verify.mobile")}}</div>
        <div class="str flex">
          <input type="text" class="inp" :placeholder="n_mobile" disabled />
        </div>
      </li>
      <li class="db" v-if="curRegType == 1">
        <div class="name">{{$t("verify.email")}}</div>
        <div class="str flex">
          <input type="text" class="inp" :placeholder="n_email" disabled />
        </div>
      </li>
      <li class="db">
        <div class="name">{{ context }}</div>
        <div class="str flex">
          <input
            type="number"
            class="inp"
            v-model="myCode"
            oninput="if(value.length>6)value=value.slice(0,6)"
            :placeholder="$t('login.code')"
          />
        </div>
        <!--<div class="v">-->
          <!--<button-->
            <!--class="btn2"-->
            <!--:disabled="isCountdown"-->
            <!--@click="send_click()"-->
          <!--&gt;{{ isCountdown ? `${second}` : $t("login.send_code") }}</button>-->
        <!--</div>-->
        <div class="v" v-if="!time_show">
          <button class="btn2" @click="send_click()">{{$t('login.send_code')}}</button>
        </div>
        <div class="v" v-show="time_show" >
          <button class="btn2">
            <van-count-down ref="countDown" :time="time"  format="ss" @finish='finish_time'>
              <template v-slot="timeData">
                <span>{{ timeData.seconds }} <var>s</var></span>
              </template>
            </van-count-down>
          </button>
        </div>
      </li>
    </ul>

    <div class="container fixedBtn">
      <button class="btn" @click="handleSubmit()">{{ btn }}</button>
    </div>
  </div>
</template>
<script>
const phoneReg = /^1[3-578]\d{9}$/; //大陆手机验证
const mailReg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/; //邮箱验证
export default {
  props: {
    title: {
      type: String,
      default: function (){
        return this.$t("verify.title");
      }
    },
    name: {
      type: String,
      default: function (){
        return this.$t("verify.mobile");
      }
    },
    context: {
      type: String,
      default: function (){
        return this.$t("verify.verify_code");
      }
    },
    btn: {
      type: String,
      default: function (){
        return this.$t("verify.btn_OK");
      }
    },
    is_select:{
      type:String,
      default:"true"
    },

    is_mobile:{
      type:String,
      default:""
    },
    sendType:{
      type:Number,
      default:1
    }
  },
  data() {
    return {
      time: 60 * 1000,
      time_status:false,
      time_show:false,
      isCodePass: false,
      mobileCode: "",
      isShowPicker: false,
      myCode: "",
      isCountdown: false,
      second: 60,
      dataList: [],
      curRegType:0,
      //...this.$store.state.userData,


      randomStr: '',
      captchaObj: {}

    };
  },
  created(){
    // if(this.email){
    //   this.curRegType = "1"
    // }else{
    //   this.curRegType = "0"
    // }
    // console.log(this.curRegType,'ssssssss')
      // this.initGeetestInfo();
    // this.title = this.$t("verify.title");
    // this.name = this.$t("verify.mobile");
    // this.context = this.$t("verify.verify_code");
    // this.btn = this.$t("verify.btn_OK");
  },
  watch: {
    // is_mobile(n,c){
    //   if(n == ''){
    //     this.curRegType = 1
    //   }else{
    //     this.curRegType = 0
    //   }
    // },
    curRegType(newValue, oldValue) {
      console.log(newValue,oldValue)
      this.time_show = false
      this.time_status = false
      this.myCode = ''
    },
  },

  computed: {
    n_mobile() {
      return `${this.mobile.slice(0, 3)}****${this.mobile.slice(-4)}`;
    },
    n_email() {
      return `${this.email.slice(0, 3)}****${this.email.slice(-7)}`;
    },
    mobile() {
      if(this.is_mobile == 'mearchant'){
        return this.$store.state.businessInfo.mobile
      }else{
        return this.$store.state.userData.mobile;
      }
    },
    email() {
        return this.$store.state.userData.email;
    },
    mobileAreaCode() {
      if(this.is_mobile == 'mearchant'){
        if(null == this.$store.state.businessInfo.mobileAreaCode ||
            undefined == this.$store.state.businessInfo.mobileAreaCode ||
            '' == this.$store.state.businessInfo.mobileAreaCode){
          return "86";
        }
        return this.$store.state.businessInfo.mobileAreaCode
      }else{

        if(null == this.$store.state.userData.mobileAreaCode ||
            undefined == this.$store.state.userData.mobileAreaCode ||
            '' == this.$store.state.userData.mobileAreaCode){
          return "86";
        }
        return this.$store.state.userData.mobileAreaCode;
      }
    },
  },
  methods: {
    finish_time(){
      this.time_status = false
      this.time_show = false
    },
    goBack() {
      this.$router.go(-1);
    },
    goRouter() {
      this.$router.push({
        path: this.path,
        query: this.query,
      });
    },
    timer() {
      this.timer = setInterval(() => {
        this.second -= 1;
      }, 1000);
    },
    get_phoneCode() {
      let phoneData = {
        mobile: this.mobile,
        mobileCode: this.mobileAreaCode,
        sendType: this.sendType,
      };
      this.isCountdown = true;
      if (this.curRegType == 0) {
        // if (!phoneReg.test(this.mobile)) {
        //   this.$toast("手机号格式不正确");
        //   return;
        // }
        this.$post(this.URL.user.mobile_send_code, phoneData).then((res) => {
          this.$toast(res.message);
        });
        this.timer();
      } else {
        if (!mailReg.test(this.email)) {
          //this.$toast("邮箱格式不正确");
          this.$toast(this.$t("verify.email_type_error"));
          return;
        }
        this.$post(this.URL.user.email_send_code, {
          email: this.email,
          sendType: this.sendType,
        }).then(
          (res) => {
            this.$toast(res.message);
          }
        );
        this.timer();
      }
    },
    handleSubmit() {
      if (this.myCode == "") {
        //this.$toast("验证码不能为空");
        this.$toast(this.$t("verify.verify_code_not_null"));
        return;
      }
      if (this.curRegType == 0) {
        var datas = {
          accountType:0,
          prefix:this.$store.state.userData.mobilePrefix,
          account:this.mobile,
          type:3,
          code:this.myCode,
          hasThrow:1
        };
      } else {
        var datas = {
          accountType:1,
          account:this.email,
          type:3,
          code:this.myCode,
          hasThrow:1
        };
      }

      this.$post(this.URL.user.check, datas).then((res) => {
        if (res.code == 0) {
          this.isCodePass = true;
          //this.$toast('验证成功');
          this.$toast(this.$t("verify.verify_success"));
          let data = {
            isCodePass: this.isCodePass,
            vcode: this.myCode,
            accountType:this.curRegType,
            target: this.mobile,
            mobileCode: this.mobileAreaCode,
          };
          this.$emit("getCode", data);
        } else {
          this.$toast(res.message);
        }
      });



    },
    // handleChangeCurRegType(type) {
    //   if (this.curRegType == type) {
    //     return;
    //   } else {
    //     this.myCode = "";
    //     this.curRegType = type;
    //   }
    // },

    //   geetestHandler(captchaObj){
    //   // 这里可以调用验证实例 captchaObj 的实例方法
    //   let _self = this;
    //   _self.captchaObj = captchaObj;
    //   captchaObj.onReady(function(){
    //     // 极验初始化完成
    //   }).onSuccess(function(){
    //     // 极验验证成功
    //     let result = captchaObj.getValidate();
    //
    //     if (!result) {
    //         return ;
    //     }
    //     let params = {
    //       clientType: 'h5',
    //       random: _self.randomStr,
    //       geetest_challenge: result.geetest_challenge,
    //       geetest_validate: result.geetest_validate,
    //       geetest_seccode: result.geetest_seccode
    //     };
    //     _self.$post(_self.URL.geetes.validate, params).then((data) => {
    //
    //       if('success' == data.result){
    //         _self.get_phoneCode();
    //       } else {
    //         _self.$toast.fail(data.msg);
    //       }
    //       //验证验证码
    //     });
    //
    //   }).onError(function(){
    //       //your code
    //       console.log("Error ");
    //   });
    //
    // },






    // initGeetestInfo(){
    //   let f_t = (new Date()).getTime();
    //   this.randomStr = f_t + '' + this.common.GetRandomNum(0,9999);
    //   let params = {
    //     clientType: 'h5',
    //     t: f_t,
    //     random: this.randomStr,
    //   };
    //
    //   let lang = this.common.GetGeetestLang();
    //   this.$get(this.URL.geetes.captcha, params).then((data) => {
    //     console.log("data = ", data);
    //     //请检测data的数据结构， 保证data.gt, data.challenge, data.success有值
    //       initGeetest({
    //           gt: data.gt,
    //           challenge: data.challenge,
    //           offline: !data.success,
    //           lang: lang,
    //           new_captcha: data.new_captcha,
    //           product: "bind", // 产品形式，包括：float，popup
    //           remUnit: (document.documentElement.clientWidth / 7.5) / window.devicePixelRatio
    //       },
    //         this.geetestHandler)
    //   });
    // },
    send_click() {
      if (this.curRegType == 0) {
        if (this.mobile.toString().length < 7 || this.mobile.toString().length > 12) {
          this.$toast.fail(this.$t('login.p_input_sure_mobile'));
          return;
        }
      } else {
        if (!mailReg.test(this.email)) {
          this.$toast(this.$t("verify.email_type_error"));
          return;
        }
      }


      this.send_code()
      // this.captchaObj.verify();
    },


    send_code() {
      //判断在不在60秒内

      if(this.time_status){
        //this.$toast("操作频繁.晚点再试");
        this.$toast.success(this.$t('edit_mail.code_timeout'));
      }else{

        if (this.curRegType == 0) {
          // if (phoneReg.test(this.mobile)) {
          if (this.mobile.toString().length > 6 && this.mobile.toString().length < 13) {
            var send_api = this.URL.user.send_code;
            var send_arr = {
              accountType:0,
              prefix:this.$store.state.userData.mobilePrefix,
              account: this.mobile,
              type: 3,
            };
          } else {
            //this.$toast("请输入正确的手机号");
            this.$toast.fail(this.$t('login.p_input_sure_mobile'));
            return;
          }
        } else {
          if (mailReg.test(this.email)) {
            var send_api = this.URL.user.send_code;
            var send_arr = {
              accountType:1,
              account: this.email,
              type: 3,
            };
          } else {
            //this.$toast("请输入正确的邮箱");
            this.$toast.fail(this.$t('login.p_input_sure_email'));
            return;
          }
        }





        this.$post(send_api, send_arr).then((res) => {
          if (res.code == 0) {
            //this.$toast.success('发送成功');
            this.$toast.success(this.$t('edit_mail.code_send_successed'));
            this.myCode = res.data.code
            this.time_show = true
            this.time_status = true
            this.$refs.countDown.reset();
            this.$refs.countDown.start();
          } else {
            this.$toast(res.message)
          }
        });





      }

    },



  },


  mounted() {
    if (this.mobile != '') {
      this.curRegType = 0;
    } else {
      this.curRegType = 1;
      // if (this.mobile != null || this.mobile != "") {
      //
      // } else {
      //   this.curRegType = 0;
      // }
    }
  },
};
</script>
<style lang="less" scoped>

#app {
  .bgs {
    background: #f4f5f9;
    padding-bottom: .5rem;

  }
  .title {
    margin-top: 0.2rem;
    height: 0.66rem;
    font-size: 0.3rem;
    font-weight: 400;
    text-align: center;
  }
  .mobileCode {
    width: 0.7rem;
    text-align: left;
    margin-left: 0.3rem;
    position: relative;
  }
  .regType {
    display: flex;
    align-items: start;
    flex-direction: column;
    width: 100%;
    padding: 0 0.2rem;
    background-color: #fff;
    margin: 0.2rem 0;
    span {
      display: block;
      width: 100%;
      position: relative;
      text-align: left;
      height: 1rem;
      display: flex;
      align-items: center;
    }
    .van-radio {
      margin-left: auto;
    }
  }
  .list {
    margin-top: 0.2rem;
    li {
      min-height: 1rem;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px -0.02rem 0px 0px rgba(243, 243, 243, 1);
      .name {
        font-size: 0.3rem;
        font-weight: 400;
        color: rgba(20, 25, 31, 1);
      }
      .str {
        .inp {
          background-color: #ffffff;
          text-align: right;
          width: 100%;
          font-size: 0.3rem;
          border: 0;
        }
      }
    }
  }
  .btn2 {
    height: 0.66rem;
    border-radius: 0.08rem;
    border: 0.02rem solid rgba(31, 159, 255, 1);
    background: #fff;
    margin-left: 0.2rem;
    font-size: 0.26rem;
    color: #1f9fff;
    padding: 0 0.2rem;

  }
  .fixedBtn {
    button {
      margin-top: 0.38rem;
    }
  }
}
</style>
